package cn.iocoder.yudao.module.iot.gateway.protocol.tcp.detector;

import io.vertx.core.net.NetSocket;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MagicByteDetectionStrategy implements ProtocolDetectionStrategy {
    private final Map<String, byte[]> magicBytesMap = new HashMap<>();
    private final Set<String> supportedProtocols;

    public MagicByteDetectionStrategy() {
        // 初始化支持的协议类型
        supportedProtocols = Collections.singleton("magic-byte");
    }

    public void registerMagicBytes(String protocolType, byte[] magicBytes) {
        magicBytesMap.put(protocolType, magicBytes);
    }

    @Override
    public String detectProtocol(byte[] data, NetSocket socket) {
        // 基于数据头部魔术值识别
        return detectByMagicBytes(data);
    }

    @Override
    public int getPriority() {
        return 10;
    }

    @Override
    public Set<String> getSupportedProtocols() {
        return supportedProtocols;
    }

    private String detectByMagicBytes(byte[] data) {
        if (data == null || data.length == 0) {
            return null;
        }

        for (Map.Entry<String, byte[]> entry : magicBytesMap.entrySet()) {
            byte[] magicBytes = entry.getValue();
            if (data.length >= magicBytes.length) {
                boolean match = true;
                for (int i = 0; i < magicBytes.length; i++) {
                    if (data[i] != magicBytes[i]) {
                        match = false;
                        break;
                    }
                }
                if (match) {
                    return entry.getKey();
                }
            }
        }
        return null;
    }
}